package snail.controllers;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import snail.model.*;
import javax.servlet.http.*;
import org.hibernate.Session;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import snail.data.ArticleDAO;
import snail.hibernate.util.HibernateUtil;
import snail.misc.PreparedModelAndView;

public class ArticlesController extends MultiActionController {

    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {

        ModelAndView mv = new PreparedModelAndView("articles/index", request);

        String keywords = request.getParameter("q");
        int category = 0;

        if (request.getParameter("c") != null) {
            try {
                category = Integer.parseInt(request.getParameter("c"));
            } catch (NumberFormatException ex) {
                category = 0;
            }
        }



        mv.addObject("q", keywords);
        mv.addObject("currentCategory", category);


        List<Article> articles;
        if (keywords != null && keywords.length() > 0) {
            articles = new ArticleDAO().search(keywords, category);
        } else {
            articles = new ArticleDAO().getByCategoryId(category);
        }

        mv.addObject("articles", articles);

        return mv;
    }

    public ModelAndView details(HttpServletRequest request, HttpServletResponse response, String errorMsg) {


        int id = Integer.parseInt(request.getParameter("id"));


        Article a = new ArticleDAO().getById(id);



        ModelAndView mv = new PreparedModelAndView("articles/details", request);


        if (a.getExpireDate().before(new Date())) {
            mv.addObject("expired", true);
        }

        java.io.File f = new java.io.File(getServletContext().getRealPath("/Auctions/Images/Thumb/" + id + ".png"));

        if (f.exists()) {
            mv.addObject("hasImage", true);
        }


        mv.addObject("ratings", a.getCreatorUser().getUserRatings().size());
        User user = (User) request.getSession().getAttribute("user");

        if (user != null) {
            mv.addObject("loggedin", true);
            if (a.getHighestBid() != null && a.getHighestBid().getUser().getUserId() == user.getUserId()) {
                mv.addObject("lead", true);
            }
        }
        if (errorMsg != null) {
            mv.addObject("error", errorMsg);
        }

        mv.addObject("article", a);
        mv.addObject("noOfBids", a.getBids().size());
        return mv;
    }

    public ModelAndView bid(HttpServletRequest request, HttpServletResponse response) throws IOException {

        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return new UserController().login(request, response, "../articles/details/" + request.getParameter("id"));
        }

        if (request.getMethod().equals("POST")) {

            int id = Integer.parseInt(request.getParameter("id"));
            int amount;
            try {
                amount = Integer.parseInt(request.getParameter("bid"));
            } catch (NumberFormatException ex) {
                amount = 0;
            }



            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();

            Article article = (Article) session.load(Article.class, id);

            if (article.getExpireDate().before(new Date())) {
                response.sendRedirect("../details/" + id);
            }

            if (article.getCreatorUser().getUserId() == user.getUserId()) {
                return details(request, response, "Men lille gobben nu bjuder du på din egna auktion!");
            }

            int prevbid = 0;
            if (article.getHighestBid() != null) {
                prevbid = article.getHighestBid().getBid();
                if (article.getHighestBid().getUser().getUserId() == user.getUserId()) {
                    return details(request, response, "Du leder redan den är auktionen!");
                }
            }

            if (amount > prevbid && amount >= article.getStartPrice()) {

                if (user == null) {
                }

                Bid bid = new Bid();
                bid.setUser(user);
                bid.setUserId(user.getUserId());
                bid.setArticle(article);
                bid.setBid(amount);

                session.save(bid);
                session.getTransaction().commit();

            } else {
                int minsta = prevbid < article.getStartPrice() ? article.getStartPrice() : prevbid;
                if (minsta == prevbid) {
                    minsta++;
                }


                return details(request, response, "Lägsta bud du kan lägga är " + minsta + " SEK.");

            }
            response.sendRedirect("../details/" + id);
        } else {
            response.sendRedirect("../details/" + request.getParameter("id"));
        }


        return null;
    }
}
